import { userStore } from '~/store'
import { createRouter, createWebHashHistory } from 'vue-router'
import { App } from 'vue'
import routes from './main'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

let dynamicRoutesInited = false

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})

const allowList = ['/login']

export function setupRouter(app: App) {
  app.use(router)
}

router.beforeEach(async (to) => {
  try {
    NProgress.start()
    if (allowList.indexOf(to.path) >= 0) {
      return true
    }
    if (dynamicRoutesInited === false) {
      const user = userStore()
      await user.getMenu() //这里除了获取菜单之外，更重要的构建dynamicRouter
      dynamicRoutesInited = true
      return to.path //加载router后重新进入
    }
    return true
  } catch (error: any) {
    return false
  } finally {
    NProgress.done()
  }
})

export default router
